import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { ZHRequestConfig, ZHRequestInterceptors } from './type'
class ZHRequest {
  instance: AxiosInstance
  interceptors?: ZHRequestInterceptors
  constructor(config: ZHRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config?.interceptors
    // 单个实例添加拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptors,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responsetInterceptors,
      this.interceptors?.responseInterceptorCatch
    )
    //为所有实列去添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res.data
      },
      (err) => {
        return err
      }
    )
  }
  request<T = any>(config: ZHRequestConfig<T>): Promise<T> {
    // 单独请求的拦截器
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config)
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responsetInterceptors) {
            res = config.interceptors.responsetInterceptors(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  get<T = any>(config: ZHRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T = any>(config: ZHRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
  delete<T = any>(config: ZHRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }
  patch<T = any>(config: ZHRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default ZHRequest
